/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.elcom.dailyexpress.requestprocess2;

import com.elcom.emocbc.cbcresponseparser.cbcresponse.getmessagestatus.BroadcastInformation;
import com.elcom.emocbc.cbcresponseparser.cbcresponse.getmessagestatus.CbcMessageStatusPerBsc;
import com.elcom.emocbc.cbcresponseparser.cbcresponse.getmessagestatus.CbcMessageStatusResult;
import com.elcom.emocbc.cbcresponseparser.cbcresponse.getmessagestatus.GetMessageStatusResponse;
import com.elcom.emocbc.cbcresponseparser.cbcresponse.getmessagestatus.GetMessageStatusResponseParser;
import com.elcom.emocbc.cbcresponseparser.cbcresponse.getmessagestatus.NumberOfBroadcastCompleteList;
import com.elcom.emocbc.cbcresponseparser.cbcresponse.getmessagestatus.ReturnValue;
import com.elcom.emocbc.cbcresponseparser.cbcresponse.getmessagestatus.StatusPerBsc;
import com.elcom.emocbc.dbmapping.persistence.CellPersistence;
import com.elcom.emocbc.dbmapping.tables.pojos.Cell;
import com.google.common.collect.Lists;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.xpath.XPathExpressionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author GiangLT
 */
public class GetMessageStatusProcessor extends RequestProcessor {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    public GetMessageStatusProcessor(HttpServletRequest request, HttpServletResponse response) {
        super(request, response);
    }

    @Override
    public void process() throws Exception {
        String messageId = request.getParameter("messageid");
        logger.debug("[SMSCB {}]Processing GetMessageStatusRequest with msgId {}", smscbCenterId, messageId);
        String bsc = MessageIdCache.getInstance().remove(Long.valueOf(messageId));
        logger.debug("[MsgId {}]Found bscId {} from cache", messageId, bsc);
        returnXmlResponse(Lists.newArrayList(bsc), messageId);
    }

    private void returnXmlResponse(List<String> bscIds, String messageId) throws ParserConfigurationException, XPathExpressionException, TransformerConfigurationException, IOException, TransformerException {
        logger.debug("[SMSCB {}]Building GetMessageStatusResponse for messageId {}", smscbCenterId, messageId);
        long curTime = System.currentTimeMillis();
        GetMessageStatusResponse getMessageStatusResponse = new GetMessageStatusResponse();
        getMessageStatusResponse.setRequest("getmessagestatus");
        getMessageStatusResponse.setStatus("SUCCESS");

        ReturnValue returnValue = new ReturnValue();
        returnValue.setType("list");
        getMessageStatusResponse.setReturnValue(returnValue);

        List<CbcMessageStatusResult> cbcMessageStatusResults = new ArrayList<CbcMessageStatusResult>(2);
        returnValue.setCbcMessageStatusResults(cbcMessageStatusResults);

        CbcMessageStatusResult cCbcMessageStatusResult = new CbcMessageStatusResult();
        cbcMessageStatusResults.add(cCbcMessageStatusResult);

        cCbcMessageStatusResult.setMessageId(messageId);
        cCbcMessageStatusResult.setType("COMPLETED");
        StatusPerBsc cStatusPerBsc = new StatusPerBsc();
        cCbcMessageStatusResult.setStatusPerBsc(cStatusPerBsc);

        List<CbcMessageStatusPerBsc> cCbcMessageStatusPerBscs = new ArrayList<CbcMessageStatusPerBsc>();
        cStatusPerBsc.setCbcMessageStatusPerBscs(cCbcMessageStatusPerBscs);

        CbcMessageStatusResult fCbcMessageStatusResult = new CbcMessageStatusResult();
        cbcMessageStatusResults.add(fCbcMessageStatusResult);

        fCbcMessageStatusResult.setMessageId(messageId);
        fCbcMessageStatusResult.setType("FAILURED");
        StatusPerBsc fStatusPerBsc = new StatusPerBsc();
        fCbcMessageStatusResult.setStatusPerBsc(fStatusPerBsc);

        List<CbcMessageStatusPerBsc> fCbcMessageStatusPerBscs = new ArrayList<CbcMessageStatusPerBsc>();
        fStatusPerBsc.setCbcMessageStatusPerBscs(fCbcMessageStatusPerBscs);

        for (String bscId : bscIds) {
            try {
                CbcMessageStatusPerBsc cbcMessageStatusPerBsc = new CbcMessageStatusPerBsc();
                cbcMessageStatusPerBsc.setBscId(bscId);
                NumberOfBroadcastCompleteList numberOfBroadcastCompleteList = new NumberOfBroadcastCompleteList();
                cbcMessageStatusPerBsc.setNumberOfBroadcastCompleteList(numberOfBroadcastCompleteList);

                List<BroadcastInformation> broadcastInformations = new ArrayList<BroadcastInformation>();
                numberOfBroadcastCompleteList.setBroadcastInformations(broadcastInformations);

                CellPersistence cellPersistence = new CellPersistence();
                List<Cell> cells = cellPersistence.findByBscId(bscId);
                Random rdm = new Random();
                int successCount = 0;
                int failureCount = 0;
                for (Cell cell : cells) {
                    try {
                        boolean isCompleted = rdm.nextBoolean();
                        BroadcastInformation broadcastInformation = new BroadcastInformation();
                        broadcastInformations.add(broadcastInformation);
                        broadcastInformation.setCellId(cell.getCellKey());
                        if (isCompleted) {
                            broadcastInformation.setNumberOfBroadcastComplete("1");
                            cCbcMessageStatusPerBscs.add(cbcMessageStatusPerBsc);
                            successCount++;
                        } else {
                            broadcastInformation.setCause("Cell Broadcast Not Operational");
                            fCbcMessageStatusPerBscs.add(cbcMessageStatusPerBsc);
                            failureCount++;
                        }
                    } catch (Exception ex) {
                        logger.error("", ex);
                    }

                }
                logger.debug("[MsgId {}]BSC {} has {} success, {} failure, {} total", messageId, bscId, successCount, failureCount, successCount + failureCount);
            } catch (Exception ex) {
                logger.error("", ex);
            }

        }

        logger.debug("[SMSCB {}]Gathered GetMessageStatus Objects for messageId {}, took {} ms", smscbCenterId, messageId, System.currentTimeMillis() - curTime);

        curTime = System.currentTimeMillis();
        GetMessageStatusResponseParser parser = new GetMessageStatusResponseParser();
        String xml = parser.marshall(getMessageStatusResponse);

        logger.debug("[SMSCB {}]Built GetMessageStatusResponse for messageId {}, took {} ms", smscbCenterId, messageId, System.currentTimeMillis() - curTime);
        response.getWriter()
                .println(xml);
        logger.debug("[SMSCB {}]>>> Sent GetMessageStatusResponse for messageId {}", smscbCenterId, messageId);
    }
}
